/**   
* @Title: HisBaseMapperAnnCRUD.java 
* @Package com.txby.platformApi.component.service 
* @Description: TODO(用一句话描述该文件做什么) 
* @author jacking  
* @date 2017年11月8日 上午10:41:33 
* @version V1.0   
*/
package com.txby.platformApi.component.service;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jck.mybatis.log.TxbyLogger;
import com.jck.mybatis.mapper.MybatisBaseDaoCRUD;
import com.jck.tools.ChkUtil;
import com.jck.tools.Times;
import com.txby.platformApi.component.util.RestClientUtil;
import com.txby.platformApi.data.KkDeviceInfoModel;
import com.txby.platformCore.component.util.GTPushUtil;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.data.CommonXGRetunInfo;
import com.txby.platformCore.entity.DeviceGTServerSign;
import com.txby.platformCore.entity.DeviceXGtoken;
import com.txby.platformCore.entity.SickBPdata;
import com.txby.platformCore.entity.SickBPdataRelation;

/** 
* @ClassName: HisBaseServiceAnnCRUD 
* @Description: 主要处理his多数据源事务
 */
@Service
public class SickBPdataRelationService extends MybatisBaseDaoCRUD{
	public static final String kkurl="http://kang.cn:12345/service/";
	public static final String appId="cp20171127001";
	/**
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * 绑定kk血压信息
	* @Title: getDeviceInfo 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param sickId
	* @param @param deviceSN
	* @param @param twoDimensionalCode
	* @param @return    设定文件 
	* @return CommonApiModelMapExt    返回类型 
	* @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED,timeout=36000,rollbackFor=Exception.class)
	public CommonApiModelMapExt  getDeviceInfo(Long sickId,String deviceSN,String twoDimensionalCode) throws  Exception{
		String result=RestClientUtil.getInstace().postRestDataSave(kkurl+"/thirdParty/get-device-info?appId={1}&twoDimensionalCode={2}", appId,twoDimensionalCode);
		JSONObject jo=JSON.parseObject(result);
		KkDeviceInfoModel kdm=JSON.parseObject(result, KkDeviceInfoModel.class);
		String  requestStatus=kdm.getRequestStatus();//操作结果描述，错误原因等
		Integer  errorCode=kdm.getErrorCode();//0表示成功，其他表示失败
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		mm.put(CommonApiModelMapExt.ERRCODE, 1);
		mm.put(CommonApiModelMapExt.ERRMSG, "请求血压设备绑定失败");
		if(errorCode==0){//deviceInfo
			jo=jo.getJSONObject("deviceInfo");
			BeanUtils.copyProperties(kdm, jo);
		}else{
			
			return mm;
		}
		try {
			if(kdm.getErrorCode()==0){
				Map param=new HashMap();
				param.put("sn", kdm.getSn());
				SickBPdataRelation oldsbpr=(SickBPdataRelation) findBySqlUniqueObject("select * from "+this.tableName(SickBPdataRelation.class)+" where sn=#{pojo.sn}", SickBPdataRelation.class, param );
				if(oldsbpr!=null){
					oldsbpr.setStatus(0);
					oldsbpr.setDeviceSN(deviceSN); 
					oldsbpr.setUpdateTime(new Date());
					oldsbpr.setImei(kdm.getImei());
					oldsbpr.setPhone(kdm.getPhone()); 
					oldsbpr.setType(kdm.getType());
					oldsbpr.setValidateDateTime(Times.getStringToDate(kdm.getValidateDate(), new SimpleDateFormat("yyyy-MM-dd")));
					oldsbpr.setSickId(sickId);
					this.updateObject(oldsbpr);
					
					String sql="select * from "+this.tableName(SickBPdataRelation.class)+" where deviceSN='"+deviceSN+"' and id_!="+oldsbpr.getId_()+"";
					List<SickBPdataRelation> lst=this.findBySql(sql, SickBPdataRelation.class, null);
					for(SickBPdataRelation sbr:lst){
						sbr.setDeviceSN(null);
						this.updateObject(sbr);
					}
					
				}else{
					SickBPdataRelation  sbpr=new SickBPdataRelation();
					sbpr.setCreater(sickId.toString());
					sbpr.setUpdater(sickId.toString());
					sbpr.setImei(kdm.getImei());
					sbpr.setDeviceSN(deviceSN);
					sbpr.setPhone(kdm.getPhone());
					sbpr.setQrUrl(twoDimensionalCode);
					sbpr.setSickId(sickId);
					sbpr.setStatus(0);
					sbpr.setSn(kdm.getSn());
					
					sbpr.setType(kdm.getType());
					sbpr.setValidateDateTime(Times.getStringToDate(kdm.getValidateDate(), new SimpleDateFormat("yyyy-MM-dd")));
					this.saveObject(sbpr);
					
					
				}
				
				
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "请求血压设备绑定成功");
				 
				 
 
			return mm;	
			}
		} catch (Exception e) {
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统开小差，稍后重试");
			e.printStackTrace();
		}
		
		return mm;
		
		
	}
	/**
	 * 解绑kk血压信息
	* @Title: canceDeviceInfo 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param sn
	* @param @return    设定文件 
	* @return CommonApiModelMapExt    返回类型 
	* @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED,timeout=36000,rollbackFor=Exception.class)
	public CommonApiModelMapExt  canceDeviceInfo(String sn){
		String result=RestClientUtil.getInstace().postRestDataSave(kkurl+"/thirdParty/unbind-device-by-sn?appId={1}&sn={2}", appId,sn);
		KkDeviceInfoModel kdm=JSON.parseObject(result, KkDeviceInfoModel.class);
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		mm.put(CommonApiModelMapExt.ERRCODE, 1);
		mm.put(CommonApiModelMapExt.ERRMSG, "请求血压设备解绑失败");
		try {
			if(kdm.getErrorCode()==0){
				Map param=new HashMap();
				param.put("sn", kdm.getSn());
				SickBPdataRelation oldsbpr=(SickBPdataRelation) findBySqlUniqueObject("select * from where sn=#{pojo.sn}", SickBPdataRelation.class, param );
				if(oldsbpr!=null){
					oldsbpr.setDeviceSN(null);
					this.updateObject(oldsbpr);
				} 
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "请求血压设备解绑成功");
				return mm;	
			}
		} catch (Exception e) {
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统开小差，稍后重试");
			e.printStackTrace();
		}
		
		return mm;
		
		
	}
	/**
	 * 血压接收数据
	* @Title: saveBloodpressure 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param sbp
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@Transactional(propagation = Propagation.REQUIRED,timeout=36000,rollbackFor=Exception.class)
	public Map   saveBloodpressure(SickBPdata sbp){
		Map mm = new HashMap();
		mm.put("code", 1);
		mm.put("status", "success");
		mm.put("msg", "接收成功");
		/* data
		code: (number,required) - 响应码,1成功,2拒收(不重发),其他失败(会重新发送)
		status: (string,optional) - 状态:success为成功,其他为失败
		msg: (string,optional) - 个性化响应消息
		data: (string,optional) - 其他需要返回的数据,JSON对象*/
		try {
			String sn=sbp.getSn();
			SickBPdataRelation oldsbpr=(SickBPdataRelation) findBySqlUniqueObject("select * from "+this.tableName(SickBPdataRelation.class)+" where sn='"+sn+"'", SickBPdataRelation.class, null );
			String sql="select * from "+this.tableName(SickBPdata.class)+" where bpunique='"+sbp.getBpunique()+"'";
			SickBPdata uniqueSBP=(SickBPdata) findBySqlUniqueObject(sql, SickBPdata.class, null );
			if(oldsbpr!=null){
				sbp.setDeviceSN(oldsbpr.getDeviceSN());
				sbp.setSickId(oldsbpr.getSickId());
			}

			
			if(ChkUtil.isEmpty(uniqueSBP)){
				this.saveObject(sbp);
				//数据推送血压显示
				 DeviceGTServerSign dxs=SpringContextUtils.getDeviceGTServerSign();
				 GTPushUtil xu=	GTPushUtil.getNewInstance(dxs.getAppID(), dxs.getAppKey(), dxs.getMasterSecret());
					  sql="SELECT * FROM  "+this.tableName(DeviceXGtoken.class)+" WHERE deviceSN='"+sbp.getDeviceSN()+"'";
					DeviceXGtoken  pushPoint=(DeviceXGtoken) this.findBySqlUniqueObject(sql, DeviceXGtoken.class, null);
					Map custom=new HashMap();
					Map data=new HashMap();
					custom.put("bpType", "血压类型推送");
					custom.put("discription", "测量的血压数据及时推送");
	    	/*		data.put("msgId", msgId);
	    			data.put("bedNO", curDeviceInfo.getBedNO());
	    			data.put("sickAreaName", curDeviceInfo.getSickAreaName());
	    			data.put("callTime", hc.getCreateTime());
	    			if(sbi!=null){
	    				data.put("sickName", sbi.getSickName());
	    			}else {
	    				data.put("sickName", "");
	    			}*/
	    			custom.put("data", sbp);
					if(pushPoint!=null){
						CommonXGRetunInfo  result = xu.pushSingleDeviceCustomMessage(pushPoint.getToken(), custom);
						TxbyLogger.getLogger(TxbyLogger.class).log(TxbyLogger.getTxbyLoggerLevel(), JSON.toJSONString(result));
						
					}
			}
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put("code", 0);
			mm.put("status", "fail");
			mm.put("msg", "接收失败");
			return mm;
		}
		
		
		
	}
/*	public static void main(String[] args) {
		Map custom=new HashMap();
		Map data=new HashMap();
		custom.put("bpType", "血压类型推送");
		custom.put("discription", "测量的血压数据及时推送");
		data.put("msgId", msgId);
		data.put("bedNO", curDeviceInfo.getBedNO());
		data.put("sickAreaName", curDeviceInfo.getSickAreaName());
		data.put("callTime", hc.getCreateTime());
		if(sbi!=null){
			data.put("sickName", sbi.getSickName());
		}else {
			data.put("sickName", "");
		}
		custom.put("data", null);
 
			CommonXGRetunInfo  result = GTPushUtil.getNewInstance("tqaVZzufur5mlfZDb5fo61" , "RXjecyXUuv9TkQu5EgA4L2",  "n1aLG9lgsd6QJ22EWA3CB5").pushSingleDeviceCustomMessage("32be12d6a93888211016fdd96cbeccd8", custom);
			System.out.println(result);
	}*/
	 
	 
}
